<?php

namespace app\admin\controller\goodscommon;

use app\admin\model\Classes;
use app\common\controller\Backend;
use think\Db;
use think\Session;

/**
 * 商品公共管理
 *
 * @icon fa fa-circle-o
 */
class Goodscommon extends Backend
{
    
    /**
     * Goodscommon模型对象
     * @var \app\admin\model\Goodscommon
     */
    protected $model = null;
    protected $relationSearch=true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Goodscommon;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("goodsVerifyList", $this->model->getGoodsVerifyList());
        $this->view->assign("sourceList", $this->model->getSourceList());
        $this->view->assign("isRecommentList", $this->model->getIsRecommentList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        $shop_id=Session::get('admin.id');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where(['store_id'=>$shop_id])
                ->with('store')
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->with('store')
                ->where(['store_id'=>$shop_id])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        $shop_id=Session::get('admin.id');
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
              //  halt($params);
                $date=[];
                if(!isset($params['spec_attr'])){

                  $this->error('请去添加规格');
                }
                $date['spec_value_ids']=json_encode($params['spec_attr']);
                //halt($date['spec_value_ids']);
                $date['names']=$params['names'];
                $date['keyword']=$params['keyword'];
                $date['classes_id']=$params['classes_id'];
                $date['classes_name']=model('Classes')->where(['id'=>$params['classes_id']])->value('names');
                $date['goods_jingle']=$params['goods_jingle'];
                $date['pic']=SHOPURL.$params['pic'];
                $params['pic']=SHOPURL.$params['pic'];
                if (strpos( $params['content'],'<img src="') !== false){
                    $date['content']= str_replace('<img src="','<img src="'.SHOPURL, $params['content']);
                }
                $date['sort']=$params['sort'];
                $date['status']=1;
                $date['price']=$params['price'];
                $date['store_id']=$shop_id;
            //    $date['discount_price']=$params['discount_price'];
               // $date['storage']=$params['storage'];
//                $date['sale']=$params['sale'];
                $date['is_recomment']=$params['is_recomment'];
                $date['source']=2;
                $date['createtime']=date('YmdHis');
               // $params['']
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }

                    $result = $this->model->allowField(true)->insertGetId($date);
                    if ($result !== false) {
                        if(isset($params['spec_attr'])){
                            $add=$this->addSku($params,$result);
                        }else{
                            $add=$this->addNoSku($params,$result);
                        }

                        $banner=$this->banner($params['small_pic'],$result);
                        if($add !==false && $banner!==false){
                            $this->success();
                        }else{
                            $this->error('添加商品失败');
                        }
                       // $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $classnames=new Classes();
        $classes=$classnames->where(['pid'=>0])->select();
       // halt($classes);
        $this->assign('classes',$classes);
        return $this->view->fetch();
    }
#添加没有属性的商品SKU
public function addNoSku($arr,$goods_common_id){
    $shop_id=Session::get('admin.id');
        $goods_arr=[];
    $goods_arr['goods_name']=$arr['names'];
    $goods_arr['store_id']=$shop_id;
    $goods_arr['store_name']=Db::connect('database.cheat')->name('store_join')->where(['id'=>$shop_id])->value('store_name');
  //  $goods_arr['attr_value_names']=json_encode($attr_value_names);
    $goods_arr['goods_common_id']=$goods_common_id;
    $goods_arr['goods_jingle']=$arr['goods_jingle'];
  //  $goods_arr['attr_value_ids']=json_encode($attr_value_ids);
    $goods_arr['classes_id']=$arr['classes_id'];
    $goods_arr['goods_price']=$arr['price'];
  //  $goods_arr['discount_price']=$arr['discount_price'];
   // $goods_arr['storage']=$arr['storage'];
//    $goods_arr['sale']=$arr['sale'];
    $goods_arr['goods_image']=$arr['pic'];
    $goods_arr['goods_commend']=$arr['is_recomment'];
    $goods_arr['source']=2;
    $goods_arr['createtime']=date('YmdHis');
    $res=Db::connect('database.cheat')->name('goods')->insert($goods_arr);
    if(!$res){
        return false;
    }
}
    #添加商品sku
    public function addSku($arr,$goods_common_id){
       // halt($arr['spec_attr']);

       // $attr_names=[];
        $shop_id=Session::get('admin.id');

      //  halt($attr_value_names);
     //   $attr_value_names=array_combine($attr_names,$attr_value_names);
      //  halt($attr_value_names);
        $goods_arr=[];
        $arr['spec_attr']=array_values($arr['spec_attr']);
        $data=$this->getArrSet($arr['spec_attr']);

        foreach($data as $key=>$val){
            $attr_value_ids=[];
            $attr_value_names=[];

            $goods_name=$arr['names'];
            foreach($val as $kk=>$vv){
                $names=Db::connect('database.cheat')->name('class_attr_value')->where(['id'=>$vv])->value('sp_value_name');
                $goods_name=$goods_name.' '.$names;
                $attr_value_ids[]=$vv;
                $attr_value_names[]=$names;
            }
            $goods_arr[$key]['goods_name']=$goods_name;
            $goods_arr[$key]['store_id']=$shop_id;
            $goods_arr[$key]['store_name']=Db::connect('database.cheat')->name('store_join')->where(['id'=>$shop_id])->value('store_name');
            $goods_arr[$key]['attr_value_names']=json_encode($attr_value_names);
            $goods_arr[$key]['goods_common_id']=$goods_common_id;
            $goods_arr[$key]['goods_jingle']=$arr['goods_jingle'];
            $goods_arr[$key]['attr_value_ids']=json_encode($attr_value_ids);
            $goods_arr[$key]['classes_id']=$arr['classes_id'];
            $goods_arr[$key]['goods_price']=$arr['price'];
          //  $goods_arr[$key]['discount_price']=$arr['discount_price'];
          //  $goods_arr[$key]['storage']=$arr['storage'];
           // $goods_arr[$key]['sale']=$arr['sale'];
            $goods_arr[$key]['goods_image']=$arr['pic'];
            $goods_arr[$key]['goods_commend']=$arr['is_recomment'];
            $goods_arr[$key]['source']=2;
            $goods_arr[$key]['createtime']=date('YmdHis');

        }

       // halt($goods_arr);
        $res=Db::connect('database.cheat')->name('goods')->insertAll($goods_arr);

        if(!$res){
            return false;
        }
    }
    #添加轮播图
    public function banner($small_pic,$goods_common_id){
        $small_pic=explode(',',$small_pic);
        $data=[];
        foreach($small_pic as $key=>$val){
            $data[]=[
                'small_pic'=>SHOPURL.$val,
                'goods_id'=>$goods_common_id,
                'status'=>1,

            ];
        }
        $re=Db::connect('database.cheat')->name('goodspic')->insertAll($data);
        if(!$re){
            return false;
        }
    }
#笛卡尔积
    function getArrSet($arrs,$_current_index=-1)
    {
        //总数组
        static $_total_arr;
        //总数组下标计数
        static $_total_arr_index;
        //输入的数组长度
        static $_total_count;
        //临时拼凑数组
        static $_temp_arr;

        //进入输入数组的第一层，清空静态数组，并初始化输入数组长度
        if($_current_index<0)
        {
            $_total_arr=array();
            $_total_arr_index=0;
            $_temp_arr=array();
            $_total_count=count($arrs)-1;
            $this->getArrSet($arrs,0);
        }
        else
        {
            //循环第$_current_index层数组
            foreach($arrs[$_current_index] as $v)
            {
                //如果当前的循环的数组少于输入数组长度
                if($_current_index<$_total_count)
                {
                    //将当前数组循环出的值放入临时数组
                    $_temp_arr[$_current_index]=$v;
                    //继续循环下一个数组
                    $this->getArrSet($arrs,$_current_index+1);

                }
                //如果当前的循环的数组等于输入数组长度(这个数组就是最后的数组)
                else if($_current_index==$_total_count)
                {
                    //将当前数组循环出的值放入临时数组
                    $_temp_arr[$_current_index]=$v;
                    //将临时数组加入总数组
                    $_total_arr[$_total_arr_index]=$_temp_arr;
                    //总数组下标计数+1
                    $_total_arr_index++;
                }

            }
        }

        return $_total_arr;
    }
    #获取分类
    public function getClasses(){
        $pid=input('pid');
        $data=model('Classes')->field(['id','names'])->where(['pid'=>$pid])->select();
       // halt($data);
        $str='';
        if($data){
            $str.=' 
        <div class="form-group"  id="two_class" >
            <label class="control-label col-xs-12 col-sm-2">二级分类:</label>
                <div class="col-xs-12 col-sm-8">
                    <select class="form-control form-control" required="" name="row[classes_id]" id="two">
                        <option value="0">请选择</option>';
                        foreach($data as $key=>$val) {

                 $str .= ' <option value="'.$val['id'].'">'.$val['names'].'</option>';
                        }
                $str.='</select>
                 </div>
         </div>';
        }
        return ajaxMessage($str,'ok',true);
    }
    #获取属性
    public function getClassesAttr(){
        $class_id=input('class_id');
      //  halt($class_id);
        $data=Db::connect('database.cheat')->name('class_attr')->where(['classes_id'=>$class_id])->select();
       // halt($data);
        $str='';
        if($data){
            $str.='<div class="form-group" id="three">';
            foreach($data as $key=>$val){
                $str.=' <label class="control-label col-xs-12 col-sm-2">
           '.$val['names'].':</label>
          <input type="hidden" value="'.$val['id'].'" name="row[attrId][]">
        <div class="col-xs-12 col-sm-8">';
                $value=Db::connect('database.cheat')->name('class_attr_value')->where(['class_attr_id'=>$val['id'],'classes_id'=>$class_id])->select();
                foreach($value as $kk=>$vv){
                    $str.=' <div class="checkbox-inline">';
                    $str.='<input type="checkbox" name="row[spec_attr]['.$val['id'].'][]" value="'.$vv['id'].'">';
                   // $str.='<input type="hidden" name="row[attr_value_name][]" value="'.$vv['sp_value_name'].'">';
                    $str.=' <label>'.$vv['sp_value_name'].'</label>
                </div>';
                }
                $str.='</div>';
            }
            $str.='</div>';
        }
      //  halt($str);
        return ajaxMessage($str,'ok',true);


    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            if ($count) {
                $goodsSku=model('goods')->where(['goods_common_id'=>$ids])->delete();

                if($goodsSku){
                    $this->success();
                }

            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if(strstr($params['pic'],'http')){
                    $params['pic']=$params['pic'];
                }else{
                    $params['pic']=SHOPURL.$params['pic'];
                }
                if(strstr($params['content'],'<img src="/')) {
                    if (strpos($params['content'], '<img src="') !== false) {
                        $params['content'] = str_replace('<img src="/', '<img src="' . SHOPURL.'/', $params['content']);
                    }
                }

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
       // $row['pic']=str_replace(SHOPURL,'',$row['pic']);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
